import { h } from 'vue';
import { type DataTableColumns, NButton, NPopconfirm, NTag } from 'naive-ui';
import { InventoryGoods } from '@/service/api/inventory';
import { useAuthStore } from '@/store/modules/auth';
import GoodsImage from '@/components/goods/goods-image.vue';

// 列宽管理
const COLUMN_WIDTHS_STORAGE_KEY = 'goodList_columnWidths';

// 从本地存储加载列宽设置
export const loadColumnWidths = (): Record<string, number> => {
  const stored = localStorage.getItem(COLUMN_WIDTHS_STORAGE_KEY);
  if (!stored) return {};

  try {
    return JSON.parse(stored);
  } catch (e) {
    console.error('解析列宽设置失败:', e);
    return {};
  }
};

// 获取指定列的宽度
export const getColumnWidth = (
  columnKey: string,
  defaultWidth: number,
  savedWidths: Record<string, number>
): number => {
  return savedWidths[columnKey] || defaultWidth;
};

// 保存列宽到本地存储
export const saveColumnWidth = (columnKey: string, width: number, columnWidths: Record<string, number>) => {
  columnWidths[columnKey] = width;
  localStorage.setItem(COLUMN_WIDTHS_STORAGE_KEY, JSON.stringify(columnWidths));
};

// 重置列宽设置
export const resetColumnWidths = () => {
  localStorage.removeItem(COLUMN_WIDTHS_STORAGE_KEY);
  window.$message?.success('列宽已重置为默认值');
  return {};
};

// 工具方法
export const getTagType = (tag: string) => {
  // 按照原网页端的逻辑：危险标签用error，其他用info
  const dangerTags = ['高库存', '低库存', '已过期', '置顶', '即将过期'];
  return dangerTags.includes(tag) ? 'error' : 'info';
};

export const getInventoryClass = (record: any) => {
  const reserve = Number(record.reserve) || 0;
  if (reserve < 0) return 'negative';
  if (reserve === 0) return 'zero';
  return 'positive';
};

// 删除单个商品
export const handleDeleteSingle = async (record: any, onSuccess: () => void) => {
  // 前端权限检查
  const authStore = useAuthStore();
  const rights = authStore.getInventoryRights();

  if (!rights?.good?.remove) {
    window.$message?.error('暂无删除权限');
    return;
  }

  // 显示loading提示
  const loadingMessage = window.$message?.loading(`正在删除商品: ${record.goodsName}`, {
    duration: 0 // 持续显示直到手动关闭
  });

  // 调用库存助手API，遵循项目规范，不使用try-catch包装
  const response = await InventoryGoods.deleteGood(record.objectId);

  // 关闭loading提示
  loadingMessage?.destroy();

  if (response && !response.error) {
    window.$message?.success(`成功删除商品: ${record.goodsName}`);
    onSuccess();
  } else {
    window.$message?.error('删除商品失败');
  }
};

// 商品详情
export const handleGoodDetail = (record: any) => {
  // 使用全局H5Router打开商品详情页面
  window.$h5Router?.openGoodDetail(record.objectId, {
    onError: () => {
      window.$message?.error('商品详情页面加载失败');
    }
  });
};

// 编辑商品
export const handleGoodEdit = (record: any, onSuccess?: () => void) => {
  // 使用全局H5Router打开商品编辑页面
  window.$h5Router?.openGoodEdit(record.objectId, {
    onSuccess: data => {
      window.$message?.success(`商品 ${record.goodsName} 编辑成功`);
      onSuccess?.(); // 刷新列表
    },
    onError: () => {
      window.$message?.error('商品编辑页面加载失败');
    }
  });
};

// 创建表格列配置
export const createColumns = (
  columnWidths: Record<string, number>,
  pageNum: number,
  pageSize: number,
  onDelete: () => void
): DataTableColumns => [
  {
    type: 'selection'
  },
  {
    title: '序号',
    key: 'index',
    width: getColumnWidth('index', 50, columnWidths),
    align: 'center',
    resizable: true,
    render: (_row, index) => (pageNum - 1) * pageSize + index + 1
  },
  {
    title: '操作',
    key: 'action',
    width: getColumnWidth('action', 120, columnWidths),
    align: 'center',
    resizable: true,
    render: record => {
      return h('div', { class: 'flex justify-center gap-4' }, [
        h(
          NButton,
          {
            type: 'info',
            text: true,
            size: 'small',
            class: 'h-auto px-6px py-2px text-11px min-w-auto',
            onClick: () => handleGoodDetail(record)
          },
          '详情'
        ),
        h(
          NButton,
          {
            type: 'warning',
            text: true,
            size: 'small',
            class: 'h-auto px-6px py-2px text-11px min-w-auto',
            onClick: () => handleGoodEdit(record, onDelete)
          },
          '编辑'
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDeleteSingle(record, onDelete)
          },
          {
            trigger: () =>
              h(
                NButton,
                {
                  type: 'error',
                  text: true,
                  size: 'small',
                  class: 'h-auto px-6px py-2px text-11px min-w-auto'
                },
                '删除'
              ),
            default: () => '确定删除此商品吗？'
          }
        )
      ]);
    }
  },
  {
    title: '标签',
    key: 'tags',
    width: getColumnWidth('tags', 120, columnWidths),
    align: 'center',
    resizable: true,
    render: (record: any) => {
      if (!record.tags || !Array.isArray(record.tags) || record.tags.length === 0) return '';
      return h(
        'div',
        { class: 'flex flex-wrap justify-center gap-1' },
        record.tags.map((tag: string) =>
          h(
            NTag,
            {
              type: getTagType(tag),
              size: 'small',
              class: 'text-11px px-6px py-1px rounded-3px font-500'
            },
            () => tag
          )
        )
      );
    }
  },
  {
    title: '商品编号',
    key: 'productNumber',
    width: getColumnWidth('productNumber', 110, columnWidths),
    align: 'center',
    resizable: true,
    sorter: true
  },
  {
    title: '商品名称',
    key: 'goodsName',
    width: getColumnWidth('goodsName', 200, columnWidths),
    align: 'left',
    resizable: true,
    sorter: true,
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '图片',
    key: 'goodsIcon',
    width: getColumnWidth('goodsIcon', 60, columnWidths),
    align: 'center',
    resizable: true,
    render: (record: any) => {
      return h(GoodsImage, {
        good: record,
        size: 32,
        enablePreview: true,
        fallbackImage: '/images/no-image.png'
      });
    }
  },
  {
    title: '品牌',
    key: 'brand',
    width: getColumnWidth('brand', 80, columnWidths),
    align: 'center',
    resizable: true,
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '分类',
    key: 'classText',
    width: getColumnWidth('classText', 100, columnWidths),
    align: 'center',
    resizable: true,
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '库存',
    key: 'reserve',
    width: getColumnWidth('reserve', 100, columnWidths),
    align: 'center',
    resizable: true,
    sorter: true,
    render: (record: any) => {
      const reserveValue = record.reserve !== undefined ? record.reserve : 0;
      return h(
        'div',
        { class: 'flex justify-center' },
        h(
          'span',
          {
            class: `font-600 px-6px py-2px rounded-3px text-12px ${
              getInventoryClass(record) === 'negative'
                ? 'bg-red-50 text-red-600'
                : getInventoryClass(record) === 'zero'
                  ? 'bg-yellow-50 text-yellow-600'
                  : 'bg-green-50 text-green-600'
            }`
          },
          String(reserveValue)
        )
      );
    }
  },
  {
    title: '成本价',
    key: 'costPriceShow',
    width: getColumnWidth('costPriceShow', 80, columnWidths),
    align: 'center',
    resizable: true
  },
  {
    title: '批发价',
    key: 'scalePriceShow',
    width: getColumnWidth('scalePriceShow', 80, columnWidths),
    align: 'center',
    resizable: true
  },
  {
    title: '零售价',
    key: 'retailPriceShow',
    width: getColumnWidth('retailPriceShow', 80, columnWidths),
    align: 'center',
    resizable: true
  },
  {
    title: '单位',
    key: 'packingUnit',
    width: getColumnWidth('packingUnit', 60, columnWidths),
    align: 'center',
    resizable: true,
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '规格',
    key: 'packModel',
    width: getColumnWidth('packModel', 120, columnWidths),
    align: 'center',
    resizable: true,
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '条码',
    key: 'productCode',
    width: getColumnWidth('productCode', 140, columnWidths),
    align: 'center',
    resizable: true,
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '位置',
    key: 'position',
    width: getColumnWidth('position', 100, columnWidths),
    align: 'center',
    resizable: true,
    sorter: true,
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '创建时间',
    key: 'createdAt',
    width: getColumnWidth('createdAt', 160, columnWidths),
    align: 'center',
    resizable: true,
    sorter: true
  }
];
